package com.taikang.controller;

import com.alibaba.fastjson.JSON;
import com.taikang.entity.Employee;
import com.taikang.entity.ReportRecord;
import com.taikang.entity.TaskRecord;
import com.taikang.service.EmployeeService;
import com.taikang.service.TaskService;
import com.taikang.util.FileUpload;
import com.taikang.util.ResponseData;
import com.taikang.util.Status;
import com.taikang.util.TypeEnum;
import com.taikang.util.page.Pagination;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import sun.misc.BASE64Decoder;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * Created by zhai on 16/5/11.
 */
@Controller
public class EmployeeController {

    private EmployeeService employeeService;
    private TaskService taskService;

    @Autowired
    public void setTaskService(TaskService taskService) {
        this.taskService = taskService;
    }

    @Autowired
    public void setEmployeeService(EmployeeService employeeService) {
        this.employeeService = employeeService;
    }

    @RequestMapping(value = "/employee/login")
    @ResponseBody
    public Object employeeLogin(@RequestParam("username") String username, @RequestParam("password") String password) {
        ResponseData responseData = new ResponseData();
        Employee employee = employeeService.employeeLogin(username, password);
        if (null == employee) {
            responseData.setStatus(Status.error);
            responseData.setMsg("用户名密码错误");
        } else {
            Integer status = employee.getStatusID();
            if (status == 2) {
                responseData.setStatus(Status.error);
                responseData.setMsg("员工已离职,无法登录");
            } else {
                responseData.setStatus(Status.success);
                responseData.setData(employee);
                responseData.setMsg("登录成功");
            }
        }
        return responseData;
    }

    @RequestMapping(value = "/employee/salary")
    @ResponseBody
    public Object getSalaryList(@RequestParam("employeeId") Integer employeeId,
                                @RequestParam(value = "recordId", required = false) Integer recordId,
                                @RequestParam(value = "page", required = false, defaultValue = "1") Integer page,
                                @RequestParam(value = "size", required = false, defaultValue = "3") Integer size) {
        ResponseData responseData = new ResponseData();
        responseData.setStatus(Status.success);
        responseData.setData(employeeService.getSalaryByEmployeeId(employeeId, recordId, page, size));
        return responseData;
    }

    @RequestMapping(value = "/employee/train")
    @ResponseBody
    public Object getTrainList(@RequestParam("employeeId") Integer employeeId,
                               @RequestParam(value = "courseId", required = false) Integer courseId,
                               @RequestParam(value = "page", required = false, defaultValue = "1") Integer page,
                               @RequestParam(value = "size", required = false, defaultValue = "3") Integer size) {
        ResponseData responseData = new ResponseData();
        Employee employee = employeeService.getEmployeeById(employeeId);
        if (null == employee) {
            responseData.setStatus(Status.error);
            responseData.setMsg("员工不存在");
        } else {
            Integer status = employee.getStatusID();
            if (status == 2) {
                responseData.setStatus(Status.error);
                responseData.setMsg("员工已离职,无法登录");
            } else {
                Integer agentId = employee.getAgentID();
                responseData.setStatus(Status.success);
                Object o = employeeService.getTrainInfo(agentId, courseId, page, size);

                if (o instanceof Pagination) {
                    Pagination pagination = (Pagination) o;
                    if (null == pagination.getDataList() || 0 == pagination.getDataList().size()) {
                        responseData.setStatus(Status.error);
                        responseData.setMsg("暂无数据");
                        return responseData;
                    }
                }
                responseData.setStatus(Status.success);
                responseData.setData(o);
            }
        }
        return responseData;
    }

    @RequestMapping(value = "/train/enroll")
    @ResponseBody
    public Object enrollTrain(@RequestParam("employeeId") Integer employeeId, @RequestParam("courseId") Integer courseId) {
        ResponseData responseData = new ResponseData();
        boolean flag = employeeService.enrollTrain(employeeId, courseId);
        responseData.setStatus(flag ? Status.success : Status.error);
        responseData.setMsg(flag ? "报名成功" : "报名失败,请稍后再试");
        return responseData;
    }

    @RequestMapping(value = "/employee/task")
    @ResponseBody
    public Object getTaskInfo(@RequestParam("employeeId") Integer employeeId,
                              @RequestParam(value = "taskId", required = false) Integer taskId,
                              @RequestParam(value = "page", required = false, defaultValue = "1") Integer page,
                              @RequestParam(value = "size", required = false, defaultValue = "3") Integer size) {
        ResponseData responseData = new ResponseData();
        Object o = employeeService.getTaskInfo(employeeId, taskId, page, size);
        if (o instanceof Pagination) {
            Pagination pagination = (Pagination) o;
            if (null == pagination.getDataList() || 0 == pagination.getDataList().size()) {
                responseData.setStatus(Status.error);
                responseData.setMsg("暂无数据");
                return responseData;
            }
        }
        responseData.setStatus(Status.success);
        responseData.setData(o);
        return responseData;
    }

    @RequestMapping(value = "/task/choose")
    @ResponseBody
    public Object taskChoose(@RequestParam("taskId") Integer taskId, @RequestParam("choose") Integer choose) {
        ResponseData responseData = new ResponseData();
        TaskRecord record = (TaskRecord) employeeService.getTaskInfo(null, taskId, null, null);
        if (choose == 1) {
            TypeEnum.TaskStatusEnum statusEnum = TypeEnum.TaskStatusEnum.ALREADY;
            record.setStatus(statusEnum.getStatusName());
            record.setStatusID(statusEnum.getStatusID());
        } else if (choose == 2) {
            TypeEnum.TaskStatusEnum statusEnum = TypeEnum.TaskStatusEnum.AGAIN;
            record.setStatus(statusEnum.getStatusName());
            record.setStatusID(statusEnum.getStatusID());
            record.setEmployeeID(null);
        } else if (choose == 3) {
            TypeEnum.TaskStatusEnum statusEnum = TypeEnum.TaskStatusEnum.PROCESS;
            record.setStatus(statusEnum.getStatusName());
            record.setStatusID(statusEnum.getStatusID());
            record.setEmployeeID(null);
        }
        employeeService.updateTask(record);
        responseData.setStatus(Status.success);
        responseData.setMsg("操作成功");
        return responseData;
    }

    @RequestMapping(value = "/task/report")
    @ResponseBody
    public Object taskReport(@RequestParam("taskId") Integer taskId, @RequestParam("explain") String explain,
                             @RequestParam("pictures") String pictures, HttpServletRequest request) throws IOException {
        ResponseData responseData = new ResponseData();
        TaskRecord record = (TaskRecord) employeeService.getTaskInfo(null, taskId, null, null);
        ReportRecord exist = taskService.getByTaskId(taskId);
        if (null != exist) {
            responseData.setStatus(Status.error);
            responseData.setMsg("该任务已经生成过报告");
            return responseData;
        }
        ReportRecord reportRecord = new ReportRecord();
        reportRecord.setOrderID(record.getOrderID());
        reportRecord.setEmployeeID(record.getEmployeeID());
        reportRecord.setUserID(record.getUserID());
        reportRecord.setDate(record.getPushDate());
        reportRecord.setContent(explain);
        reportRecord.setTaskID(taskId);
        reportRecord.setStartTime(record.getStartTime());
        reportRecord.setEndTime(record.getEndTime());
        StringBuffer pictureUrls = new StringBuffer();
        List<String> files = JSON.parseArray(pictures, String.class);
        if (null != files && files.size() > 0) {
            for (String picture : files) {
                GenerateImage(picture, String.valueOf(new Date().getTime()), request);
            }
        }
        //String url = pictureUrls.substring(0, pictureUrls.length() - 1);
        //reportRecord.setPicture(url);
        responseData.setStatus(Status.success);
        responseData.setData(reportRecord);
        responseData.setMsg("任务报告生成成功");
        return responseData;
    }

    public boolean GenerateImage(String imgStr, String img_name, HttpServletRequest request) {   //对字节数组字符串进行Base64解码并生成图片
        if (imgStr == null) //图像数据为空
            return false;
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            //Base64解码
            byte[] b = decoder.decodeBuffer(imgStr);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {//调整异常数据
                    b[i] += 256;
                }
            }

            //生成jpeg图片
            String path = request.getSession().getServletContext().getRealPath("/image") + "/" + img_name + ".png";
            File file = new File(path);
            file.createNewFile();
            System.out.println(file.getAbsolutePath());
            OutputStream out = new FileOutputStream(path);
            out.write(b);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
            System.out.println("异常。。。。。。。。。。。。");
            return false;
        }
    }
}
